<!--
    /**
     * 下拉选择树形组件，下拉框展示树形结构，提供选择某节点功能，方便其他模块调用
     * @author ljn
     * @date 2019-02-23
     * 调用示例：
     * <tree-select :height="400" // 下拉框中树形高度
     * :width="200" // 下拉框中树形宽度
     * :data="data" // 树结构的数据
     * :defaultProps="defaultProps" // 树结构的props
     * multiple   // 多选
     * checkStrictly // 多选时，严格遵循父子不互相关联
     * :nodeKey="nodeKey"   // 绑定nodeKey，默认绑定'id'
     * :checkedKeys="defaultCheckedKeys"  // 传递默认选中的节点key组成的数组
     * @popoverHide="popoverHide"> // 事件有两个参数：第一个是所有选中的节点ID，第二个是所有选中的节点数据
     * </tree-select>
     */
-->
<template>
  <div>
    <div
      class="mask"
     
      @click="isShowSelect = !isShowSelect"
    ></div>
    <el-popover
      placement="bottom-start"
      :width="width"
      trigger="manual"
      v-model="isShowSelect"
      @hide="popoverHide"
    >
      <el-input
        placeholder="输入关键字"
        v-model="filterText"
      >
      </el-input>

      <el-tree
        class="common-tree"
        :style="style"
        ref="tree"
        :data="dataTree"
        :load="loadNode"
        lazy
        :props="defaultProps"
        :show-checkbox="multiple"
        :node-key="nodeKey"
        :check-strictly="checkStrictly"
        default-expand-all
        :expand-on-click-node="false"
        :default-checked-keys="defaultCheckedKeys"
        :highlight-current="true"
        :default-expanded-keys="defaultExpand"
        @node-click="handleNodeClick"
        @check-change="handleCheckChange"
      ></el-tree>
      <el-select
        :style="selectStyle"
        slot="reference"
        ref="select"
        v-model="selectedData"
        @click.native="isShowSelect = !isShowSelect"
        class="tree-select w100p"
      >

      </el-select>
    </el-popover>
  </div>
</template>
 
<script>
import * as areaApi from "@/api/area";
export default {
  name: "tree-select",
  props: {
    // 树结构数据
    // data: {
    //   type: Array,
    //   default() {
    //     return [];
    //   },
    // },
    defaultProps: {
      type: Object,
      default() {
        return {};
      },
    },
    // 配置是否可多选
    multiple: {
      type: Boolean,
      default() {
        return false;
      },
    },
    nodeKey: {
      type: String,
      default() {
        return "id";
      },
    },
    // 显示复选框情况下，是否严格遵循父子不互相关联
    checkStrictly: {
      type: Boolean,
      default() {
        return false;
      },
    },
    // 默认选中的节点key数组
    checkedKeys: {
      type: Array,
      default() {
        return [];
      },
    },
    width: {
      type: Number,
      default() {
        return 250;
      },
    },
    height: {
      type: Number,
      default() {
        return 300;
      },
    },
  },
  data() {
    return {
      filterText: "",
      defaultCheckedKeys: [],
      isShowSelect: false, // 是否显示树状选择器
      options: [null, null, null, null],
      selectedData: '', // 选中的节点
      style: "width:" + this.width + "px;" + "height:" + this.height + "px;",
      selectStyle: "width:" + (this.width + 24) + "px;",
      checkedIds: [],
      checkedData: [],
      dataTree: [],
      defaultExpand: [],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    if (this.checkedKeys.length > 0) {
      if (this.multiple) {
        this.defaultCheckedKeys = this.checkedKeys;
        this.selectedData = this.checkedKeys.map((item) => {
          var node = this.$refs.tree.getNode(item);
          return node.label;
        }).join('');
      } else {
        var item = this.checkedKeys[0];
        this.$refs.tree.setCurrentKey(item);
        var node = this.$refs.tree.getNode(item);
        this.selectedData = node
          ? node.map((item) => {
              return item.label;
            }).join('')
          : '';
      }
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;

      return data.name.indexOf(value) !== -1;
    },
    //初始化
    handleInit(row) {
      this.dataTree = row;
      this.selectedData = '';
      this.options = [null, null, null, null];
    },
    async loadNode(node, resolve) {
      let _this = this;
      if (node.level === 0) {
        console.log("this.data", _this.dataTree);
        const { data } = await areaApi.getProvinceList();
        _this.dataTree = data.map((item) => {
          item.children = [];
          return item;
        });
        return resolve(_this.dataTree);
      } else {
        return resolve(node.data.children || []);
      }
    },
    popoverHide() {
      if (this.multiple) {
        this.checkedIds = this.$refs.tree.getCheckedKeys(); // 所有被选中的节点的 key 所组成的数组数据
        this.checkedData = this.$refs.tree.getCheckedNodes(); // 所有被选中的节点所组成的数组数据
      } else {
        this.checkedIds = this.$refs.tree.getCurrentKey();
        this.checkedData = this.$refs.tree.getCurrentNode();
      }
      this.$emit("popoverHide", this.checkedIds, this.checkedData);
    },
    // 节点被点击时的回调,返回被点击的节点数据
    async handleNodeClick(item, node) {
      let _this = this;
      if (!this.multiple) {
        let tmpMap = {};
        tmpMap.value = node.key;
        tmpMap.label = node.label;
        this.options[node.level - 1] = tmpMap;

        if (node.level == 4) {
          this.isShowSelect = !this.isShowSelect;
          _this.selectedData = _this.options
            .map((item) => {
              return item && item.label;
            })
            .join("");
        }
        if (node.level === 1) {
          const { data } = await areaApi.getCityList({
            provinceCode: node.key,
          });
          let arrList = data;
          arrList = arrList.map((items) => {
            items.children = [];
            return items;
          });
          item.children = arrList;
          item = Object.assign({});
          this.dataTree = Object.assign([], this.dataTree);
          for (let i = 0; i < this.options.length; i++) {
            if (i > node.level - 1) {
              this.options[i] = null;
            }
          }
        } else if (node.level === 2) {
          for (let i = 0; i < this.options.length; i++) {
            if (i > node.level - 1) {
              this.options[i] = null;
            }
          }
          const { data } = await areaApi.getRegionList({
            cityCode: node.key,
          });
          let arrList = data;
          arrList = arrList.map((items) => {
            items.children = [];
            return items;
          });
          item.children = arrList;
          item = Object.assign({});
          this.dataTree = Object.assign([], this.dataTree);
        } else if (node.level === 3) {
          for (let i = 0; i < this.options.length; i++) {
            if (i > node.level - 1) {
              this.options[i] = null;
            }
          }
          const { data } = await areaApi.getTownList({
            regionCode: node.key,
          });
          let arrList = data;
          arrList = arrList.map((items) => {
            items.children = [];
            return items;
          });
          item.children = arrList;
          item = Object.assign({});
          this.dataTree = Object.assign([], this.dataTree);
        }
      }
    },
    // 节点选中状态发生变化时的回调
    handleCheckChange() {
      var checkedKeys = this.$refs.tree.getCheckedKeys(); // 所有被选中的节点的 key 所组成的数组数据
      this.options = checkedKeys.map((item) => {
        var node = this.$refs.tree.getNode(item); // 所有被选中的节点对应的node
        let tmpMap = {};
        tmpMap.value = node.key;
        tmpMap.label = node.label;
        return tmpMap;
      });
      this.selectedData = this.options.map((item) => {
        return item.label;
      }).join('');
    },
  },
  watch: {
    isShowSelect(val) {
      // 隐藏select自带的下拉框
      this.$refs.select.blur();
    },
    async checkedKeys(val) {
      if (val.length > 0) {
        if (this.multiple) {
          this.defaultCheckedKeys = val;
          this.selectedData = val.map((item) => {
            var node = this.$refs.tree.getNode(item);
            return node.label;
          }).join('');
        } else {
          this.options = [];
          const provinceListRes = await areaApi.getProvinceList();
          let provinceList = provinceListRes.data;
          let provinceListOp = provinceList.find((item) => {
            return item.code == val[3];
          });
          this.options.push({
            label: provinceListOp.name,
            value: provinceListOp.code,
          });
          const cityListRes = await areaApi.getCityList({
            provinceCode: val[3],
          });
          let cityList = cityListRes.data;
          let cityListOp = cityList.find((item) => {
            return item.code == val[2];
          });
          this.options.push({
            label: cityListOp.name,
            value: cityListOp.code,
          });
          const regionListRes = await areaApi.getRegionList({
            cityCode: val[2],
          });
          let regionList = regionListRes.data;
          let regionListOp = regionList.find((item) => {
            return item.code == val[1];
          });
          this.options.push({
            label: regionListOp.name,
            value: regionListOp.code,
          });
          const townListRes = await areaApi.getTownList({
            regionCode: val[1],
          });
          let townList = townListRes.data;
          let townListOp = townList.find((item) => {
            return item.code == val[0];
          });
          this.options.push({
            label: townListOp.name,
            value: townListOp.code,
          });
          console.log("this.options", this.options);
          this.selectedData = this.options
            .map((item) => {
              return item.label;
            })
            .join("");
          provinceList = provinceList.map((item) => {
            if (item.code == val[3]) {
              item.children = cityList;
            }
            return item;
          });
          cityList = cityList.map((item) => {
            if (item.code == val[2]) {
              item.children = regionList;
            }
            return item;
          });

          regionList = regionList.map((item) => {
            if (item.code == val[1]) {
              item.children = townList;
            }
            return item;
          });
          let _this = this;
          _this.dataTree = provinceList;
          _this.$nextTick(() => {
            var item = val[0];
            _this.$refs.tree.setCurrentKey(item);
            // var node = _this.$refs.tree.getNode();
          });
        }
      }
    },
  },
};
</script>
 
<style scoped>
.mask {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  opacity: 0;
}
.common-tree {
  overflow: auto;
}
</style>
 
<style>
.tree-select .el-select__tags .el-tag .el-tag__close {
  display: none;
}
.tree-select .el-select__tags .el-tag .el-icon-close {
  display: none;
}
</style>